---
--类名: LaunchController.lua
--创建日期: 2015-4-2
--创建人: 陈小虎
--功能描述:
--修改内容：
--修改日期:
--修改人:
--修改备注:
--

local FieldManager_updateFrame = FieldManager.updateFrame
-- local FieldManager_debugUpdateUsers = FieldManager.debugUpdateUsers
local FieldManager_updateFrameLower = FieldManager.updateFrameLower

local BattleManager_isInBattle = BattleManager.isInBattle
local BattleManager_updateBattle = BattleManager.updateBattle
local MapManager_updateFrame = MapManager.updateFrame

local startTouchTime = 0
local isTouchCharacter = false
local startTouchMove = false

local LaunchController = class("LaunchController",function()
	return display.newNode()
end)

function LaunchController:ctor()
    self._updateTime = 0

    -- self:init()

    self:enableNodeEvents()
end

function LaunchController:addTouchLayer()
    --屏幕触摸
    local layer = display.newNode()
    layer:setContentSize(display.width, display.height)
    self:addChild(layer,SceneZOrder.touchZOrder)
    self.mTouchLayer1 = layer

    local stopMoveTouch = false
    local lastTouchTime = 0
    local lastDistance = 0
    local touchBeginTime = 0
    local isMapZoom = false
    local clickTime = 0.2
    local threeClickTime = 1.0
    local isClickMoved = false
    local isLongPressed = false
    local mutiTouch = false
    local isCameraZoom = false

    local function canHandleTouch()
        if UIHandler:getSystemUi():isHaveSystemUI()
            or FieldManager:isStopEvent() then
            return false
        end
        return true
    end

    local function clearTouchParams()
        stopMoveTouch = false
        lastTouchTime = 0
        lastDistance = 0
        touchBeginTime = 0
        isMapZoom = false
        isClickMoved = false
        isLongPressed = false
        mutiTouch = false
        isCameraZoom = false
        layer:stopAllActions()
    end

    local function touchesBegan(touches, event)
        if UIHandler:getSystemUi():isHaveSystemUI() then return false end
        local desktopCtl = UIHandler:getDesktopController()
        if not desktopCtl then return false end

        if not StoryManager:isEnterStoryMode()
            and not BattleManager:isWaitBattle()
            and not BattleManager:isBattle()
            and not StoryManager:isExitStoryModeDelay() then
            if not UIHandler:isDesktopShow() then
                stopMoveTouch = true
            end
            if not MapManager:isChangeMap() then
                UIHandler:showDesktop()
            end
        end
        if stopMoveTouch then
            return false
        end
        touchBeginTime = app:getTime()
        lastTouchTime = touchBeginTime
        isMapZoom = false

        local touch = touches[1]
        local locationX, locationY = touch:getLocation2()

        local function call()
            isLongPressed = true
            UIHandler:hideHeadMenu()
            self:onTouch("began", locationX, locationY)
        end
        local sequenceAction = cc.Sequence:create(cc.DelayTime:create(clickTime),cc.CallFunc:create(call))
        layer:stopAllActions()
        layer:runAction(sequenceAction)
        if #touches >= 2 then
            mutiTouch = true
            layer:stopAllActions()
        end
    end

    local function touchesMoved(touches, event)
        if stopMoveTouch then
            return
        end

        local tLen = #touches
        if tLen >= 3 then
            return
        end

        local touchTime = app:getTime() - touchBeginTime

        if #touches > 1 and
            (not StoryManager:isStopStoryEvent()
            or (StoryManager:isStopStoryEvent()
            and BattleManager:isInBattle())) then
            layer:stopAllActions()
            MapManager:pauseRunCameraZoomForEvent(true)
            isMapZoom = true
            local touch1 = touches[1]
            local touch2 = touches[2]

            local location1X ,location1Y = touch1:getLocation2()
            local location2X ,location2Y = touch2:getLocation2()
            local subX = location1X-location2X
            local subY = location1Y-location2Y

            local distance = math.sqrt( subX * subX + subY * subY )
            local zoomIn = true
            if not lastDistance then
                lastDistance = distance
                return
            else
                if distance > lastDistance then
                    zoomIn = true
                else
                    zoomIn = false
                end
            end

            local speed = 0.2
            local dt = (app:getTime() - lastTouchTime) * 5
            dt = (dt > 0.2) and 0 or dt
            lastDistance = distance
            lastTouchTime = app:getTime()

            if dt > 0 then
                if zoomIn then
                    MapManager:mapTouchZoomIn(dt,speed)
                else
                    MapManager:mapTouchZoomOut(dt,speed)
                end
                isCameraZoom = true
            end

        elseif canHandleTouch() then
            if touchTime > clickTime and not isMapZoom then
                local touch = touches[1]
                local locationX,locationY = touch:getLocation2()
                self:onTouch("moved", locationX, locationY)
                isClickMoved = true
            end
        end
    end

    local function touchesEnded(touches, event)
        if isCameraZoom then
            isCameraZoom = false
            MapManager:saveMapLayerScale()
        end
        if not canHandleTouch() then
            clearTouchParams()
            return
        end

        if stopMoveTouch then
            stopMoveTouch = false
            return
        end

        if mutiTouch then
            clearTouchParams()
            return
        end

        MapManager:setExtraScaleRate(0)
        if not FieldManager:isStopTouches() and isMapZoom then
            MapManager:pauseRunCameraZoomForEvent(false)
        end

        local clickTotalTime = app:getTime() - touchBeginTime
        if clickTotalTime <= clickTime then
            local touch = touches[1]
            local locationX,locationY = touch:getLocation()
            self:onTouch("began", locationX, locationY)
            self:onTouch("ended", locationX, locationY)
            clearTouchParams()
        elseif isClickMoved or isLongPressed then
            local touch = touches[1]
            local locationX, locationY = touch:getLocation()
            self:onTouch("ended", locationX, locationY)
            clearTouchParams()
        end
    end

    local function touchesCancelled()
        clearTouchParams()
    end

    local touchListener = cc.EventListenerTouchAllAtOnce:create()
    touchListener:registerScriptHandler(touchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN)
    touchListener:registerScriptHandler(touchesMoved,cc.Handler.EVENT_TOUCHES_MOVED)
    touchListener:registerScriptHandler(touchesEnded,cc.Handler.EVENT_TOUCHES_ENDED)
    touchListener:registerScriptHandler(touchesCancelled,cc.Handler.EVENT_TOUCHES_CANCELLED)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(touchListener, layer)


    local resetLayer = display.newNode()
    resetLayer:setContentSize(display.width, display.height)
    self:addChild(resetLayer,SceneZOrder.resetTouchZOrder)
    self.mTouchLayer2 = resetLayer

    local debugTouchStartTime = 0
    local function debugVisibility(touch)
        local interval = app:getTime() - debugTouchStartTime
        if interval >= 0 then
            local locationX,locationY = touch:getLocation()
            if locationX >= display.width / 3 and locationX <= display.width / 3 * 2 then
                if locationY >= display.height / 2 then
                    if UIHandler:isDesktopShow() then
                        debugTouchStartTime = app:getTime()
                        NpcManager:setDebugForVideo(true)
                        UIHandler:hideDesktop()
                        NpcManager:allNpcUpHeadNodeVisibility(false)
                    else
                        debugTouchStartTime = app:getTime()
                        NpcManager:setDebugForVideo(false)
                        UIHandler:showDesktop()
                        NpcManager:allNpcUpHeadNodeVisibility(true)
                    end
                end

            end
        end
    end
    local function resetTouchBegan(touch, event)
        if not StoryManager:isEnterStoryMode() and not BattleManager:isBattle() then

            return true
        end
        return false
    end
    local function resetTouchMoved(touch, event)
        if not StoryManager:isEnterStoryMode() and not BattleManager:isBattle() then
            
        end
    end
    local function resetTouchEnded(touch, event)
        if not StoryManager:isEnterStoryMode() and not BattleManager:isBattle() then
            if DEBUG == -1 then
                debugVisibility(touch)
            end
        end
    end

    local resetTouchListener = cc.EventListenerTouchOneByOne:create()
    resetTouchListener:setSwallowTouches(false)
    resetTouchListener:registerScriptHandler(resetTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN)
    resetTouchListener:registerScriptHandler(resetTouchMoved,cc.Handler.EVENT_TOUCH_MOVED)
    resetTouchListener:registerScriptHandler(resetTouchEnded,cc.Handler.EVENT_TOUCH_ENDED)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(resetTouchListener, resetLayer)

    local touchZoomLayer = display.newLayer()
    touchZoomLayer:setContentSize(display.width, display.height)
    self:addChild(touchZoomLayer,SceneZOrder.resetTouchZOrder + 1)
    self.mTouchLayer3 = touchZoomLayer

    local touchParLayer = display.newNode()
    touchParLayer:setContentSize(display.width, display.height)
    self:addChild(touchParLayer,SceneZOrder.touchParZOrder)
    self.mTouchLayer4 = touchParLayer

    local clickTimes = 0 -- 点击次数
    local cdTime = 1 -- 清除CD
    self.tickNumId = self:schedule(function()
        cdTime = cdTime - 1
        if 0 >= cdTime then
            clickTimes = 0
            cdTime = 1
        end
    end,1)
    display.nodeTouchOneByOne(touchParLayer, function(x,y)
        UIHandler:setLastTouchPosition(x,y)
        UIHandler:playTouchParticle(x,y)
        if 50 >= x and 50 >= y then
            clickTimes = clickTimes + 1
        end
        return true
    end, function()
        UIHandler:stopTouchParticle()
        if clickTimes >= 5 then
            app:sendMsg("IMRoomController", "showView")
        end
    end, false, function(x,y)
        UIHandler:resetTouchParticlePosition(x,y)
    end, function()
        UIHandler:stopTouchParticle()
    end)

end

function LaunchController:addChessTouchLayer()
    local layer = display.newNode()
    layer:setContentSize(display.width, display.height)
    self:addChild(layer,SceneZOrder.desktopZOrder)
    self.chessTouchLayer = layer

    self.chessListener = display.nodeTouchOneByOne(layer,
        function(x,y)
            local isHit = FieldManager:isTouchChessCharacter(x, y)
            self.chessListener:setSwallowTouches(isHit)
            return isHit
        end,
        function(x,y)
            self.chessListener:setSwallowTouches(false)
            FieldManager:testTouchChessCharacter(x, y)
        end)
end

function LaunchController:removeTouchLayer()
    self:removeChild(self.mTouchLayer1)
    self.mTouchLayer1 = nil
    self:removeChild(self.mTouchLayer2)
    self.mTouchLayer2 = nil
    self:removeChild(self.mTouchLayer3)
    self.mTouchLayer3 = nil
    self:removeChild(self.mTouchLayer4)
    self.mTouchLayer4 = nil

    if not cc.isDead(self.chessTouchLayer) then
        self:removeChild(self.chessTouchLayer)
    end
    self.chessListener = nil
    self.chessTouchLayer = nil
end

local layer_3_touchEnabled
function LaunchController:disableTouchLayer()
    local eventDispatcher = self:getEventDispatcher()
    if not cc.isDead( self.mTouchLayer1 ) then
        eventDispatcher:pauseEventListenersForTarget( self.mTouchLayer1 )
    end
    if not cc.isDead( self.mTouchLayer2 ) then
        eventDispatcher:pauseEventListenersForTarget( self.mTouchLayer2 )
    end
    if not cc.isDead( self.mTouchLayer3 ) then
        layer_3_touchEnabled = self.mTouchLayer3:isTouchEnabled()
        self.mTouchLayer3:setTouchEnabled( false )
    end
    if not cc.isDead( self.chessTouchLayer ) then
        eventDispatcher:pauseEventListenersForTarget( self.chessTouchLayer )
    end
end
function LaunchController:resetTouchLayerEnable()
    local eventDispatcher = self:getEventDispatcher()
    if not cc.isDead( self.mTouchLayer1 ) then
        eventDispatcher:resumeEventListenersForTarget( self.mTouchLayer1 )
    end
    if not cc.isDead( self.mTouchLayer2 ) then
        eventDispatcher:resumeEventListenersForTarget( self.mTouchLayer2 )
    end
    if not cc.isDead( self.mTouchLayer3 ) and nil ~= layer_3_touchEnabled then
        self.mTouchLayer3:setTouchEnabled( layer_3_touchEnabled )
    end
    if not cc.isDead( self.chessTouchLayer ) then
        eventDispatcher:resumeEventListenersForTarget( self.chessTouchLayer )
    end
end


function LaunchController:init()
    -- self:addTouchLayer()
    NodeFactory:setUiParent(self)
    NpcManager:setBaseNode(self)
    NpcManager:init()
    FieldManager:init()

    TeamManager:init()

    UIHandler:setUiParent(self)
    UIHandler:init()

    local eventNode = display.newNode()
    self:addChild(eventNode)
    DoEventHandler.setActionNode(eventNode)
    DoEventHandler.setLaunchController(self)
    DoEventHandler.init()

    StoryManager:setBaseNode(self)

    BattleManager:setParent(self)
    BattleManager:init()

    DungeonManager:init()

    local node = display.newNode()
    self:addChild(node)
    ScriptManager:setActionNode(node)

    MapManager:setParent(self)

    FieldManager:stopTouch(true)
    self:addListeners()
end

function LaunchController:onEnter()

end

function LaunchController:onExit()
    self._haveSetTargetNode = false

    if self._udHandlers and type(self._udHandlers) == "table" then
        for k,handler in pairs(self._udHandlers) do
            UD:unChanged(k,handler)
        end
    end
    self._udHandlers = nil

    UD.setting:unChangedAutoPlayWeather()

    self:stopUpdateFrame()

    for i,v in ipairs(self._emHandles or {}) do
        EM:remove(v)
    end
    for i,handle in ipairs(self._fieldHandles or {}) do
        FieldManager:removeEventListener(handle)
    end

    NodeFactory:setUiParent(nil)

    UD.setting:unChangedShowPlayerUphead()
end

function LaunchController:startUpdateFrame()
    -- 注册帧事件
    self:scheduleUpdate( handler(self, self.updateFrame))
end

function LaunchController:stopUpdateFrame()
    self:unscheduleUpdate()
end

function LaunchController:updateFrame(dt)
    if BattleManager_isInBattle(BattleManager) then
        MapManager_updateFrame(MapManager, dt)
        BattleManager_updateBattle(BattleManager, dt)
        return
    end

    self._updateTime = self._updateTime + dt
    if self._updateTime > Constant.LowerUpdateInterval then
        FieldManager_updateFrameLower(FieldManager, self._updateTime)
        self._updateTime = 0
    end
--    FieldManager_debugUpdateUsers(FieldManager, dt)
    FieldManager_updateFrame(FieldManager, dt)
end

function LaunchController:addListeners()
    self:initAllListeners()

    local emHandles = {}

    -- 第一次进入地图
    emHandles[#emHandles + 1] = EM:on("onMapChanged", function(eventName, isFirstIntoGame)
        if isFirstIntoGame then
            -- 做一些数据的初始化
            
            -- 获取秘境副本
            SecretManager:init()
            -- -- 初始化成就
            -- AchievementManager:reqAchievements()

            -- 请求称号
            UD:initTitleData() --只有首次创建user的时候才需要清空称号
            UD:reqTitleData()

            app:sendMsg("CaptainController", "reqRoomData", UD:getUid())

            -- 任务数据初始化
            TaskManager:init()
            TaskManager:relaunchGetTaskReward()

            -- 请求传奇武器数据
            app:sendMsg("LegendModel", "C2S_GetLegendInfo")

            -- 理发店解锁信息
            app:sendMsg("AvatarShopModel", "C2S_BarberShopUnlock")

            -- 请求世界boss开启状态
            app:sendMsg("BossModel", "reqWorldBossStatus")

            -- 请求强化大师数据
            app:sendMsg("NewBagModel", "reqQueryRecastMaster")

            -- 其他活动数据初始化
            app:sendMsg("RewardModel", "initActivityList")

            -- 特权礼包数据
            app:sendMsg("RewardModel", "reqPrivilegeInfoForPayNotice")
            app:sendMsg("RewardModel", "checkShowAdvert", 1002)
            
            -- 报纸数据初始化
            HistoryManager:initNewsPaper()
            HistoryManager:showNewsPaperTips()

            UD.redPoint:init()
        end
    end)

    -- 断线重连处理逻辑
    emHandles[#emHandles + 1] = EM:on("onReconnectSuccessed", function(event)
        if BattleManager:isBattle() then
            BattleManager:goOutBattle(nil,nil,true)
        end

        -- 关闭对战loading
        app:sendMsg("PvpController", "closeLoadingView")

        app:dispatchCustomEvent("EVENT_UPDATE_TRACKLIST")
        StoryManager:clearAllStatus()
--        TaskManager:updateBaseShowIds()
        NpcManager:updateResourcePointNpcs()
--        NpcFactory:createAllMapBaseNpc(MapManager:getMapId())
--        NpcFactory:createTaskBaseNpcs(MapManager:getMapId())
        NpcManager:updateGrayBattleNpcs()
        TaskManager:relaunchGetTaskReward()
--        TaskManager:updateTaskOperation(UD:getCurTask(), "insert")
        -- ScriptManager:refreshScripts()

        -- 断线重连的时候，开启主线任务追踪点击
        DoEventHandler.setTaskMaskFlag(false)
        UIHandler:enableMainTaskTrackingTouch()

        if MapManager:isInDungeonMap() then
            DungeonManager:deleteAllBNpcs()
            app.session:request("pb_dungeon.C2S_GetDungeonInfo",{},
                function(msg) end, {block = false})
        end

        local character = FieldManager:getMyCharacter()
        if not cc.isDead(character) then
            character:setAllOpacity(255)
            character:setVisible(true)

            local hasBattle, enterBattleInfo = UD:hasBattle(MapManager:getMapId())
            if hasBattle and not MapManager:isChangeMap() then
                UD:clearBattle()
                BattleManager:setEnterBattleInfo(enterBattleInfo)
                BattleManager:prepareBattle(true)
            end
        else
            print("============> my character is nil!")
        end

        -- 断线重连时世界boss再次请求
        local bossModel = app:getInst("BossModel")
        if bossModel then
            if bossModel:getWorldBossIsOpen() and bossModel:worldBossIsEnded() then
                -- 服务器数据还是开启状态而客户端数据显示已经活动结束就再次请求一遍世界boss开启状态
                app:sendMsg("BossModel", "reqWorldBossStatus")
            end
        end
    end)

    UD.setting:onAutoPlayWeatherChanged(function(play)
        if not play then
            FieldManager:getWeatherSystem():closeWeather()
        else
            FieldManager:getWeatherSystem():setMap(MapManager:getMap())
            FieldManager:getWeatherSystem():initWeatherSystem()
            FieldManager:getWeatherSystem():playWeather()
        end
    end)

    local udHandlers = {}
    udHandlers["npc"] = UD:onChanged("npc",function(uid,npc,opt)
        if opt=="insert" then
            local npc = NpcFactory:createServiceInsertNpc(npc)
        elseif opt=="delete" then
            NpcManager:deleteNpcFromService(uid)
        end
    end)

    udHandlers["task"] = UD:onChanged("task",function(tasks,opt)
        local index = 0
        local bNeedUpdateTrackList = false
        for k,task in pairs(tasks) do
            index = index + 1
            FieldManager:updateAutoWayParams(task)
            TaskManager:updateTaskOperation(task, opt, index)
            ScriptManager:updateTaskScript(task)
            app:dispatchCustomEvent("EVENT_TASK_TRACK",{task = task})

            --如果主线任务或者正在追踪的任务有更新才去更新追踪列表
            if task:isMain() or TaskManager:isNeedTrack(task:getId()) then
                bNeedUpdateTrackList = true
            end
        end

        if opt == "update" then
            app:sendMsg("TaskController", "updateNewTasks", tasks)
            app:sendMsg("DailyController", "updateNewTasks", tasks)
        end

        -- 更新主界面追踪列表
        if bNeedUpdateTrackList then
            app:dispatchCustomEvent("EVENT_UPDATE_TRACKLIST")
        end
    end)

    udHandlers["partner"] = UD:onChanged("partner",function(uid,tid,partner,opt)
        if opt == "insert" then
            local partnerConfig = GD:queryPartnerById(tid)
            if partnerConfig and partnerConfig.ID and tonumber(partnerConfig.messageShow) ~= 1 then
                app:popMessage("getnewmercenary", {L(partnerConfig.name)})
                local message = string.format(L("tips_3000318"),L(partnerConfig.name))
                app:sendMsg("IMModel", "addSystemMsg", message)
            end
        end
    end)

    udHandlers["mount"] = UD:onChanged("mount",function(uid,mount,opt)
        if opt == "insert" or opt == "delete" then
            -- FieldManager:updateMountSpeed() -- 坐骑速度会通过mapUpdate来进行更新
        end
    end)

    self._udHandlers = udHandlers

----------------------ui响应 临时----------------------------
    emHandles[#emHandles+1] = EM:on("onTrackingWay",function(name,params)
        local isFinding,noError = FieldManager:taskTrackingAutoWayFinding(params.trackNpcId,params.trackTaskId,params.autoStartEvents,params.isTracking,params.isLegionTrack,params.immediately)
        if params.findCall then
            if isFinding and params.trackTaskId then
                app:dispatchCustomEvent("EVENT_TRACK_STATUS",{taskId = params.trackTaskId})
            end
            params.findCall(isFinding,noError)
        end
    end)

    self._emHandles = emHandles

    self._fieldHandles = {}
    self._fieldHandles[#self._fieldHandles + 1] = FieldManager:addEventListener("onAddTouchLayer", function(event)
        self:addTouchLayer()
    end)
    self._fieldHandles[#self._fieldHandles + 1] = FieldManager:addEventListener("onRemoveTouchLayer", function(event)
        self:removeTouchLayer()
    end)
end

function LaunchController:showInfoGetAfterBattle()
end

function LaunchController:showInfoGetAfterStory()
end

function LaunchController:endCharacterMove(touchPoint)
    if cc.isDead(FieldManager:getMyCharacter()) then return end

    local interval = app:getTime() - startTouchTime

    local targetX = 0

    local targetPos
    if interval >= 0.2 or not touchPoint then
        targetPos = cc.p(FieldManager:getCharacterX(),0)
    else
        targetPos = MapManager:getTargetPosition(touchPoint)
    end
    targetX = targetPos.x

    FieldManager:setTargetX(targetX)
    FieldManager:touchEndOperate()
end

function LaunchController:onTouch(event, x, y)
    if NpcManager:isNpcExcuteEvents() then return false end
    if FieldManager:isStopTouches() then return false end
    if app:getInst( "NewActivityDungeonsModel" ):isLionHornMap() then return false end --  狮心号角中不能移动

    local touchPoint = cc.p(x,y)
    -- if event == 'began' or event == 'ended' then
    if event == 'began' then
        isTouchCharacter = FieldManager:isTouchCharacter(touchPoint,event)
        if isTouchCharacter then
            self:endCharacterMove(touchPoint)
            return false
        end

        if FieldManager:isTouchMyCharacter(touchPoint) then
            isTouchCharacter = false
            self:endCharacterMove(touchPoint)
            return false
        end
    else
        isTouchCharacter = false
    end

    if event == 'began' and not isTouchCharacter then
        startTouchTime = app:getTime()
        startTouchMove = true
    end

    if not startTouchMove then
        return false
    end

    if event == 'ended' then
        startTouchMove = false
        self:endCharacterMove(touchPoint)
    elseif startTouchMove then
        local targetPos = MapManager:getTargetPosition(touchPoint)
        if not targetPos then
            targetPos = cc.p(FieldManager:getCharacterX(),0)
        end
    
        local characterPosX = FieldManager:getCharacterX()
        if FieldManager:isTouchMyCharacterXAxis(targetPos.x,event) then
            return false
        end

        if x < display.cx - 80 or x > display.cx + 80 then
            if characterPosX < targetPos.x then
                characterPosX = MapManager:getMapWidth()
            elseif characterPosX > targetPos.x then
                characterPosX = 0
            end
            FieldManager:setTargetX(characterPosX)
            DoEventHandler.moveOperateAtGather()
        end
    end

    FieldManager:breakTransfer()

    return true
end

function LaunchController:initAllListeners()
    UD.setting:onShowPlayerUpheadChanged(function(isShow)
        FieldManager:updateAllCharactersUpHead(isShow)
    end)


--    app:addCustomEventListener("EVENT_OVER_CUR_TALK",function(event)
--        local touch = false
--        if event._usedata then
--            touch = event._usedata.touch
--        end
--        -- DoEventHandler.setTouchForNextTalk(touch)
--        -- FieldManager:hideAllBubble()
--        DoEventHandler.setTalkTouchOver(touch)
--        DoEventHandler.overCurrentTalkEvent()
--    end,self)

    app:addCustomEventListener("EVENT_START_EVENTS",function(event)
        if not event._usedata then return end
        local events = event._usedata.events
        local npcId = event._usedata.npcId
        DoEventHandler.startEvents(clone(events),npcId)
    end,self)

    app:addCustomEventListener("EVENT_NEXT_EVENTS",function(event)
        local touch = false
        if event._usedata then
            touch = event._usedata.touch
        end
        DoEventHandler.setTouchForNextTalk(touch)
        FieldManager:hideAllBubble()
        DoEventHandler.foreCurrentEventsOver()
    end,self)

--    app:addCustomEventListener("EVENT_GUILD_IN_BANQUEST",function(event)
--        print("inBanquest")
--        print( " ------------->>>>> 旧接口：EVENT_GUILD_IN_BANQUEST" )
--    end,self)

--    app:addCustomEventListener("EVENT_DARK_THUNDER",function(event)
--        BattleManager:prepareBattle()
--    end,self)

--    app:addCustomEventListener("EVENT_ACTIVITY_EVENT_NPC",function(event)
--        if not event._usedata then return end
--        local npcId = event._usedata.npcId
--        NpcFactory:createActivityNpc(npcId)
--    end,self)

--    app:addCustomEventListener("EVENT_ACTIVITY_SCRIPT",function(event)
--        if not event._usedata then return end
--        local npcId = event._usedata.npcId
--        local script = event._usedata.script
--        local aConfig = event._usedata.aConfig
--        ScriptManager:initActivityScripts(npcId,script,aConfig)
--        -- ACM:activityWeatherControl(aConfig,true)
--    end,self)

--    app:addCustomEventListener("EVENT_STOP_ACTIVITY_SCRIPT",function(event)
--        if not event._usedata then return end
--        local npcId = event._usedata.npcId
--        local script = event._usedata.script
--        local aConfig = event._usedata.aConfig
--        local npc = NpcManager:getNpcById(npcId)
--        if npc then
--            npc:stopActivityAction()
--        end
--        -- app:dispatchCustomEvent("EVENT_REFRESH_SCRIPT",{force = true})
--        -- ACM:activityWeatherControl(aConfig,false)
--    end,self)

    local function teamUpdate()
        TeamManager:updateTeamEntities()
    end
    app:addCustomEventListener("EVENT_TEAM_UPDATE",teamUpdate,self)
    teamUpdate()

--    app:addCustomEventListener("EVENT_REFRESH_SCRIPT",function(event)
--        local force = false
--        if event._usedata then
--             force = event._usedata.force
--        end
--        if force then
--             ScriptManager:refreshScripts()
--        else
--             ScriptManager:runRefreshScriptsAction()
--        end
--    end,self)

--    app:addCustomEventListener("EVENT_REFRESH_SINGLE_SCRIPT",function(event)
--         local npc = nil
--         if event._usedata then
--             npc = event._usedata.npc
--         end
--         ScriptManager:initSingleScripts(npc)
--    end,self)

    app:addCustomEventListener("EVENT_REFRESH_DUNGEON_SCRIPT",function(event)
        local npc = nil
        if event._usedata then
            npc = event._usedata.npc
        end
        if not npc then return end

        local npcConfig = NpcManager:getNpcConfigById(npc:getId())
        if npcConfig and npcConfig.ID then
            St.loadDungeonScript(npcConfig)
        end
    end,self)

    app:addCustomEventListener("EVENT_CHANGE_MAP",function(event)
        if not event._usedata then
            return
        end
        -- 如果当前在模拟剧情，这里就直接返回
        if DoEventHandler.isSimulation then return end

        FieldManager:breakTransferStatus()
        MapManager:gotoMap(event._usedata)
    end,self)

    UIHandler:addFloatFrameListener()
end

return LaunchController
